package com.imooc.security.demo.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 文件的上传下载
 *
 * @author JackYang
 * @description:
 * @create: 2020/6/14 11:42
 */
@RestController
@RequestMapping("/file")
public class FileController {
    
    @PostMapping("/up")
    public String upLoadFile(MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws IOException {
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(file.getSize());
        
        //获取项目绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/upLoadFiles");
        File file1 = new File(realPath);
        //判断该路径是否存在
        if (!file1.exists()) {
            //创建文件目录
            file1.mkdirs();
        }
        String fileName = System.currentTimeMillis() + ".txt";
        //执行上传操作
        file.transferTo(new File(file1, fileName));
        //upLoadFile(new File(file1,fileName))
        return "ok!";
    }
    
    @GetMapping("/{id}")
    public void downLoadFile(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取项目绝对路径
        //String realPath = request.getSession().getServletContext().getRealPath("/upLoadFiles");
        String realPath = "C:\\Users\\10443\\AppData\\Local\\Temp\\tomcat-docbase.8794246140400108941.8080\\upLoadFiles";
        File file1 = new File(realPath);
        
        String fileName = id + ".txt";
        try (InputStream inputStream = new FileInputStream(new File(file1, fileName));
             OutputStream outStream = response.getOutputStream();
        ) {
            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            IOUtils.copy(inputStream,outStream);
            outStream.flush();
        }
    }
}
